#include "gpioControl.hpp"
#include <fstream>
#include <sstream>
#include <unistd.h>

GpioControl::GpioControl(int gpioNum) : gpioNum_(gpioNum) {
    gpioPath_ = "/sys/class/gpio/gpio" + std::to_string(gpioNum_);
    exportGpio();
}

GpioControl::~GpioControl() {
    unexportGpio();
}

bool GpioControl::exportGpio() {
    return writeToFile("/sys/class/gpio/export", std::to_string(gpioNum_));
}

bool GpioControl::unexportGpio() {
    return writeToFile("/sys/class/gpio/unexport", std::to_string(gpioNum_));
}

bool GpioControl::setDirection(const std::string& direction) {
    return writeToFile(gpioPath_ + "/direction", direction);
}

bool GpioControl::setValue(int value) {
    return writeToFile(gpioPath_ + "/value", std::to_string(value));
}

int GpioControl::getValue() {
    std::string val;
    if (!readFromFile(gpioPath_ + "/value", val)) return -1;
    return std::stoi(val);
}

bool GpioControl::writeToFile(const std::string& path, const std::string& value) {
    std::ofstream fs(path);
    if (!fs.is_open()) return false;
    fs << value;
    fs.close();
    return true;
}

bool GpioControl::readFromFile(const std::string& path, std::string& value) {
    std::ifstream fs(path);
    if (!fs.is_open()) return false;
    std::getline(fs, value);
    fs.close();
    return true;
}
